package com.szh.gulimall.order.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 延时队列、死信交换机配置
 *
 * @author: SongZiHao
 * @date: 2023/2/5
 */
@Configuration
public class RabbitMQConfig2 {

    /**
     * 延时队列: order.delay.queue
     */
    @Bean
    public Queue orderDelayQueue() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("x-dead-letter-exchange", "order-event-exchange");
        paramMap.put("x-dead-letter-routing-key", "order.release.order");
        paramMap.put("x-message-ttl", 60000);
        Queue queue = new Queue("order.delay.queue", true, false, false, paramMap);
        return queue;
    }

    /**
     * 死信队列: order.release.order.queue
     * 延时队列中的消息过期之后，会发送到死信交换机，再由交换机转到死信队列中
     */
    @Bean
    public Queue orderReleaseQueue() {
        Queue queue = new Queue("order.release.order.queue", true, false, false);
        return queue;
    }

    /**
     * topic类型交换机
     * 普通交换机、死信交换机，绑定延时队列、死信队列
     * @return
     */
    @Bean
    public Exchange orderEventExchange() {
        TopicExchange topicExchange = new TopicExchange("order-event-exchange", true, false);
        return topicExchange;
    }

    /**
     * 将订单交换机order-event-exchange与订单延时队列order.delay.queue进行绑定
     * routingKey: order.create.order
     */
    @Bean
    public Binding orderCreateBinding() {
        Binding binding = new Binding("order.delay.queue", Binding.DestinationType.QUEUE,
                "order-event-exchange", "order.create.order", null);
        return binding;
    }

    /**
     * 将订单交换机order-event-exchange与订单死信队列order.release.order.queue进行绑定
     * routingKey: order.release.order
     */
    @Bean
    public Binding orderReleaseBinding() {
        Binding binding = new Binding("order.release.order.queue", Binding.DestinationType.QUEUE,
                "order-event-exchange", "order.release.order", null);
        return binding;
    }

    /**
     * 将订单交换机order-event-exchange与库存死信队列stock.release.stock.queue进行绑定
     */
    @Bean
    public Binding orderReleaseStockBinding() {
        Binding binding = new Binding("stock.release.stock.queue", Binding.DestinationType.QUEUE,
                "order-event-exchange", "order.release.order.#", null);
        return binding;
    }
}
